package org.ecloud.oauth.server.config;

import org.ecloud.utils.StringUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties("client")
public class ClientConfig {
	
	public static final String DEF_TABLE_NAME = "client";
	public static final String FIELD_DEF_CLIENT_ID = "client_id_";
	public static final String FIELD_DEF_CLIENT_SECRET = "client_secret_";
	public static final String FIELD_DEF_STATUS = "status_";
	public static final String FIELD_DEF_EXPIRE_TIME = "expire_time_";
	
	public static final String DEF_ACCOUNT = "clientid";
	public static final String DEF_PASSWORD = "clientsecret";
	public static final String DEF_STATUS = "status";
	public static final String DEF_EXPIRE_TIME = "expiretime";
	
	private String tableName = DEF_TABLE_NAME;
	private Field field;
	/**
	 * 必须包含返回字段：clientid/clientsecret/status
	 * 所有字段都是字符类型
	 * 若该字段有值，则其它属性不生效
	 * 例：select client_key_ clientid, client_secret_ clientsecret, status_ status, expire_time_ expiretime from e_auth_client where client_key_=?
	 */
	private String sql;
	
	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	public Field getField() {
		return field;
	}
	public void setField(Field field) {
		this.field = field;
	}
	public String getSql() {
		if(StringUtil.isNotBlank(sql))
			return sql;
		
		StringBuilder builder = new StringBuilder();
		builder.append("select ");
		builder.append(this.getField().getClientId()).append(" clientid, ");
		builder.append(this.getField().getClientSecret()).append(" clientsecret, ");
		builder.append(this.getField().getExpireTime()).append(" expiretime ");
		if(StringUtil.isNotBlank(this.getField().getStatus())){
			builder.append(",").append(this.getField().getStatus()).append(" status ");
		}else{
			builder.append(", -1").append(" status ");
		}
		builder.append(" from ");
		builder.append(this.getTableName());
		builder.append(" where ").append(this.getField().getClientId()).append("=?");
		
		return builder.toString();
	}
	public void setSql(String sql) {
		this.sql = sql;
	}
	
	public static class Field {
		private String clientId = FIELD_DEF_CLIENT_ID;
		private String clientSecret = FIELD_DEF_CLIENT_SECRET;
		private String status;
		private String expireTime = FIELD_DEF_EXPIRE_TIME;
		
		public String getClientId() {
			return clientId;
		}
		public void setClientId(String clientId) {
			this.clientId = clientId;
		}
		public String getClientSecret() {
			return clientSecret;
		}
		public void setClientSecret(String clientSecret) {
			this.clientSecret = clientSecret;
		}
		public String getStatus() {
			return status;
		}
		public void setStatus(String status) {
			this.status = status;
		}
		public String getExpireTime() {
			return expireTime;
		}
		public void setExpireTime(String expireTime) {
			this.expireTime = expireTime;
		}
	}
}
